package com.sara.controller;

import com.sara.dto.ResponseBean;
import com.sara.entity.Employee;
import com.sara.entity.FixOrder;
import com.sara.entity.Order;
import com.sara.exception.ServiceException;
import com.sara.service.FixService;
import com.sara.service.OrderService;
import com.sara.util.Constant;
import com.sara.vo.OrderPartsVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.Map;

/**
 * @author Wayne
 * @date 2019/1/22
 */

@Controller
@RequestMapping("/fix")
public class FixController {

    @Autowired
    private FixService fixService;


    @GetMapping("/list")
    public String listPage(Model model){
        List<Map<String, Object>> fixOrderList = fixService.findAllOrderWithState(Order.ORDER_STATE_TRANS);
        List<Map<String, Object>> overFixOrderList = fixService.findAllOrderWithState(Order.ORDER_STATE_FIXING);

        fixOrderList.addAll(overFixOrderList);
        System.out.println("查到的结果是:" + fixOrderList);
        model.addAttribute("fixOrderList",fixOrderList);
        return "fix/list";
    }

    @GetMapping("/detail/{id:\\d+}")
    public String detailPage(@PathVariable Integer id, Model model){
        OrderPartsVo orderPartsVo = fixService.findAllOrderWithOrderId(id);
        model.addAttribute("orderPartsVo", orderPartsVo);
        model.addAttribute("curr_employee_id",getCurrEmployee().getId());
        return "fix/detail";
    }


    @GetMapping("/trans/{id:\\d+}")
    @ResponseBody
    public ResponseBean transState(@PathVariable Integer id){
        try {
            fixService.editOrderStateByOrderId(id, Order.ORDER_STATE_FIXING, getCurrEmployee());
            return ResponseBean.success();

        }catch (ServiceException e){
            return ResponseBean.error(e.getMessage());
        }
    }


    @GetMapping("/done/{id:\\d+}")
    public String done(@PathVariable Integer id, RedirectAttributes attributes){
        fixService.editOrderStateByOrderId(id, Order.ORDER_STATE_FIXED, getCurrEmployee());
        attributes.addFlashAttribute(Constant.SEND_PAGE_MASSAGE_KEY, Constant.SEND_PAGE_MASSAGE_CONTENT);
        return "redirect:/fix/list";

    }

    private Employee getCurrEmployee() {
        Subject subject = SecurityUtils.getSubject();
        Employee employee = (Employee) subject.getPrincipal();
        return employee;
    }


}
